<?php

namespace app\common\behavior;



use app\admin\model\dealer\Back;
use app\admin\model\dealer\Dealer as DealerModel;
use app\admin\model\dealer\DealerCompany;
use app\admin\model\dealer\MoneyLog;
use app\common\model\zbtask\Money;
use app\common\utils\Utils;
use think\Db;
use think\exception\ValidateException;

class DealerMoney
{
    /**
     * 给经销商反币
     * $param['money_id']  //众包费ID
     * 一周结算一次
     */
    public static function dealerBack(&$param) {
        $where['transfer_type'] = 2; //打款成功
        $where['status'] = 1; //有效
        $where['id'] = $param['money_id']; //id

        $info = Money::get($where);
        if (!$info) {
            throw new ValidateException('信息错误');
        }
        $list = DealerCompany::all(function($query) use ($info){
            $query->where(['company_id' => $info['company_id']]);
        }); //所有经销商列表

        foreach ($list as $k => $v) {
            $back = Utils::processMoney($info['money'], $v['rate'], 2);
            $dealer = DealerModel::get($v['dealer_id']);
            $before = $dealer['usermoney'];
            $after = Utils::processMoney($before, $back, '+');

            Db::startTrans();
            try{
                DealerModel::where(['id' => $v['dealer_id']])->setField('usermoney', $after);
                DealerModel::where(['id' => $v['dealer_id']])->inc('dealer_amount', $back);
                //增加余额 写入日志
                self::log($v['dealer_id'], $back, $param['money_id'],$v['rate']);
                //写入日志
                self::moneyLog($before, $after, $back, $v['dealer_id']);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                continue;
                $arr = [
                    'dealer_id' => $v['dealer_id'],
                    'money_id' => $param['money_id']
                ];
                doLog($arr, 'dealerlog');
            }
        }

    }

    private static function log($dealer_id, $money, $money_id,$rate) {
        $data['dealer_id'] = $dealer_id;
        $data['money_id'] = $money_id;
        $data['money'] = $money;
        $data['remark'] = '返佣比例：' . $rate;

        Back::create($data);
    }

    private static function moneyLog($before, $after, $money,$dealer_id) {
        $data['dealer_id'] = $dealer_id;
        $data['money'] = $money;
        $data['before'] = $before;
        $data['after'] = $after;
        $data['memo'] = '返佣';

        MoneyLog::create($data);
    }


}